import React, { useState, useEffect } from "react";
import { useParams, useNavigate, useLocation } from "react-router-dom";
import routes from "../../router/routeConfig";
import apiClient from '../../utils/apiClient';
import "./index.css";

const EditKnowledgeBasePage = () => {
  const { kbId } = useParams();
  const location = useLocation();
  const navigate = useNavigate();

  // 从URL查询参数中获取知识库名称
  const queryParams = new URLSearchParams(location.search);
  const kbNameFromUrl = queryParams.get("name") || "";

  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [isPublic, setIsPublic] = useState(true);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

  useEffect(() => {
    setIsLoading(true);

    apiClient
      .get(`/kb/${kbId}`)
      .then((response) => {
        const kbData = response.data;
        setName(kbData.name);
        setDescription(kbData.description);
        setIsPublic(kbData.isPublic);
        setIsLoading(false);
      })
      .catch((error) => {
        console.error("Failed to fetch knowledge base details:", error);
        setError("加载知识库信息失败");
        setIsLoading(false);
      });
  }, [kbId, kbNameFromUrl]);

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!name.trim()) {
      setError("知识库名称不能为空");
      return;
    }

    setIsSaving(true);
    setError("");
    setSuccess("");

    try {
      const response = await apiClient.put(`/kb/${kbId}`, {
        name,
        description,
        isPublic,
      });
      setSuccess("知识库信息已成功更新");

      // 3秒后重定向到知识库详情页
      setTimeout(() => {
        navigate(routes.knowledgeBase(kbId, name));
      }, 2000);
    } catch (err) {
      setError("更新知识库失败，请重试");
      console.error("更新知识库错误:", err);
    } finally {
      setIsSaving(false);
    }
  };

  const handleDelete = async () => {
    const confirmDelete = window.confirm(
      `确定要删除知识库 "${name}" 吗？此操作不可撤销，知识库中的所有文档都将被删除。`
    );

    if (!confirmDelete) {
      return;
    }

    setIsSaving(true);
    setError("");

    try {
      await apiClient.delete(`/kb/${kbId}`);
      navigate(routes.home);
    } catch (err) {
      setError("删除知识库失败，请重试");
      console.error("删除知识库错误:", err);
      setIsSaving(false);
    }
  };

  if (isLoading) {
    return (
      <div className="container">
        <p className="loading-text">正在加载知识库信息...</p>
      </div>
    );
  }

  return (
    <div className="container edit-kb-page">
      <div className="page-header">
        <h1>
          <i className="fas fa-edit"></i> 编辑知识库
        </h1>
        <button
          onClick={() => navigate(routes.knowledgeBase(kbId, name))}
          className="secondary"
        >
          <i className="fas fa-arrow-left"></i> 返回知识库
        </button>
      </div>

      {error && (
        <div className="alert alert-error">
          <i className="fas fa-exclamation-circle"></i> {error}
        </div>
      )}

      {success && (
        <div className="alert alert-success">
          <i className="fas fa-check-circle"></i> {success}
        </div>
      )}

      <div className="edit-kb-content">
        <form onSubmit={handleSubmit} className="edit-kb-form">
          <div className="form-group">
            <label htmlFor="kb-name">
              知识库名称 <span className="required">*</span>
            </label>
            <input
              type="text"
              id="kb-name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="例如：产品文档、开发规范"
              required
            />
          </div>

          <div className="form-group">
            <label htmlFor="kb-description">描述</label>
            <textarea
              id="kb-description"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              rows="4"
              placeholder="简要描述这个知识库的内容和用途"
            ></textarea>
          </div>

          <div className="form-group">
            <label>访问权限</label>
            <div className="radio-group">
              <div className="radio-option">
                <input
                  type="radio"
                  id="public"
                  name="visibility"
                  checked={isPublic}
                  onChange={() => setIsPublic(true)}
                />
                <label htmlFor="public">
                  <i className="fas fa-globe"></i> 公开
                  <span className="option-desc">所有人都可以查看此知识库</span>
                </label>
              </div>

              <div className="radio-option">
                <input
                  type="radio"
                  id="private"
                  name="visibility"
                  checked={!isPublic}
                  onChange={() => setIsPublic(false)}
                />
                <label htmlFor="private">
                  <i className="fas fa-lock"></i> 私有
                  <span className="option-desc">
                    只有您和被授权的用户可以查看
                  </span>
                </label>
              </div>
            </div>
          </div>

          <div className="form-actions">
            <button type="submit" className="save-btn" disabled={isSaving}>
              {isSaving ? (
                <>
                  <i className="fas fa-spinner fa-spin"></i> 保存中...
                </>
              ) : (
                <>
                  <i className="fas fa-save"></i> 保存更改
                </>
              )}
            </button>

            <button
              type="button"
              className="cancel-btn"
              onClick={() => navigate(routes.knowledgeBase(kbId, name))}
              disabled={isSaving}
            >
              取消
            </button>
          </div>
        </form>

        <div className="danger-zone">
          <h3>危险操作</h3>
          <p>以下操作不可撤销，请谨慎操作。</p>

          <button
            className="delete-btn"
            onClick={handleDelete}
            disabled={isSaving}
          >
            <i className="fas fa-trash-alt"></i> 删除此知识库
          </button>
        </div>
      </div>
    </div>
  );
};

export default EditKnowledgeBasePage;
